package com.fyzk.activity.lottery.recommend_order;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.App;
import com.fyzk.activity.lottery.basketball.JCLQFragmentActivityI;
import com.fyzk.activity.lottery.jc.football.newJz.FootballFragmentActivityI;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.utils.AppUtil;
import com.fyzk.view.DynamicLoadListener;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qinkang on 2018/8/6.
 */

public class MyBaskOrderAdapter extends RecyclerView.Adapter {
    private DynamicLoadListener mDynamicLoadListener;
    private LayoutInflater inflater;
    private Context context;
    private List<MyRecommendOrderBean> infos = new ArrayList<>();
    private int type = 0;
    private static final int VIEW_TYPE_HEAD = 1;
    private static final int VIEW_TYPE_NORMAL = 2;
    private static final int VIEW_TYPE_EMPTY = 3;
    private static final int VIEW_TYPE_NO_MORE = 4;
    private static final int VIEW_TYPE_LOADING = 5;

    public boolean mIsLoadingMore = false;
    public boolean mIsLoadMoreEnabled = true;
    private Handler mHandler = new Handler();

    public MyBaskOrderAdapter(Context context, List<MyRecommendOrderBean> infos, DynamicLoadListener listener) {
        this.context = context;
        this.infos = infos;
        inflater = LayoutInflater.from(context);
        mDynamicLoadListener = listener;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case VIEW_TYPE_HEAD:
                View head = inflater.inflate(R.layout.head_fragment_baskorder, parent, false);
                return new HeadHolder(head);
            case VIEW_TYPE_EMPTY:
                View empty = inflater.inflate(R.layout.empty_img_view, parent, false);
                return new EmptyHolder(empty);
            case VIEW_TYPE_NO_MORE:
                View noMore = inflater.inflate(R.layout.listview_bask_footer, parent, false);
                return new NoMoreHolder(noMore);
            case VIEW_TYPE_LOADING:
                View loading = inflater.inflate(R.layout.listview_footer, parent, false);
                return new Holder(loading);
            case VIEW_TYPE_NORMAL:
                View normal = inflater.inflate(R.layout.adapter_myrecommendorder, parent, false);
                return new ViewHolder(normal);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof HeadHolder) {
            HeadHolder head = (HeadHolder) holder;
            head.bind(infos.get(0).getUserBean());
        } else if (holder instanceof ViewHolder) {
            ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.bind(infos.get(position), position);
        } else if (holder instanceof NoMoreHolder) {
            NoMoreHolder empty = (NoMoreHolder) holder;
            empty.bind(infos);
        } else if (holder instanceof EmptyHolder) {
            EmptyHolder empty = (EmptyHolder) holder;
            empty.bind();
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return infos.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        Log.e("=========", getItemCount() + "");
        if (position == getItemCount() - 1) {
            if (mIsLoadMoreEnabled) {
                if (!mIsLoadingMore) {
                    mIsLoadingMore = true;
                    mDynamicLoadListener.onLoadMore();
                }
                return VIEW_TYPE_LOADING;
            } else if (getItemCount() == 1) {
                return VIEW_TYPE_EMPTY;
            } else {
                return VIEW_TYPE_NO_MORE;
            }
        } else {
            if (infos.get(position).getItem().equals("head")) {
                return VIEW_TYPE_HEAD;
            } else {
                return VIEW_TYPE_NORMAL;
            }

        }
    }

    private class EmptyHolder extends RecyclerView.ViewHolder {
        private TextView mFootballText;
        private TextView mBasketballText;
        private TextView mMyBaskText;

        public EmptyHolder(View itemView) {
            super(itemView);
            mFootballText = itemView.findViewById(R.id.baskOrderUI_footballText);
            mBasketballText = itemView.findViewById(R.id.baskOrderUI_basketballText);
            mMyBaskText = itemView.findViewById(R.id.baskOrderUI_myBaskText);
        }

        public void bind() {
            mFootballText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    App.isBaskOrder = true;
                    Intent footIntent = new Intent(context, FootballFragmentActivityI.class);
                    context.startActivity(footIntent);
                }
            });
            mBasketballText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    App.isBaskOrder = true;
                    Intent basketIntent = new Intent(context, JCLQFragmentActivityI.class);
                    context.startActivity(basketIntent);
                }
            });
            mMyBaskText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!MySharedPreferences.getInstance().getLoginStatus()) {
                        AppLotteryInfos.clear();
                        ViewCallBack.getInstance().countDownObjs.clear();
                        ActivityTaskManager.getInstance().closeAllActivity();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        return;
                    }
                    Intent intent = new Intent(context, MyBaskOrderActivity.class);
                    context.startActivity(intent);
                }
            });
        }
    }

    private class Holder extends RecyclerView.ViewHolder {

        public Holder(View itemView) {
            super(itemView);
        }

    }

    private class HeadHolder extends RecyclerView.ViewHolder {
        private TextView mFootballText;
        private TextView mBasketballText;
        private TextView mMyBaskText;
        private TextView mState;
        private TextView mHittatio;
        private TextView mProfit;
        private TextView mTotalWin;

        public HeadHolder(View itemView) {
            super(itemView);
            mFootballText = itemView.findViewById(R.id.baskOrderUI_footballText);
            mBasketballText = itemView.findViewById(R.id.baskOrderUI_basketballText);
            mMyBaskText = itemView.findViewById(R.id.baskOrderUI_myBaskText);
            mState = itemView.findViewById(R.id.tv_state);
            mHittatio = itemView.findViewById(R.id.hiscenter_hittatio_tv);
            mProfit = itemView.findViewById(R.id.hiscenter_profitratio_tv);
            mTotalWin = itemView.findViewById(R.id.hiscenter_totalWinAmount_tv);
        }

        public void bind(MyRecommendBean userBean) {
            if (userBean != null) {
                mHittatio.setText(AppUtil.formatToYuanLXS(userBean.getHitRatio() * 100) + "%");
                mProfit.setText(AppUtil.formatToYuanLXS(userBean.getProfitRatio() * 100) + "%");
                mTotalWin.setText(AppUtil.formatToYuanLXS(userBean.getTotalWinAmount() / 100) + "米");
                mState.setText(Html.fromHtml("近期状态：<font color='#FD4A4A'>" + userBean.getTotalCount() + "中" + userBean.getWinCount() + "</font>"));
            }
            mFootballText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    App.isBaskOrder = true;
                    Intent footIntent = new Intent(context, FootballFragmentActivityI.class);
                    context.startActivity(footIntent);
                }
            });
            mBasketballText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    App.isBaskOrder = true;
                    Intent basketIntent = new Intent(context, JCLQFragmentActivityI.class);
                    context.startActivity(basketIntent);
                }
            });
            mMyBaskText.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!MySharedPreferences.getInstance().getLoginStatus()) {
                        AppLotteryInfos.clear();
                        ViewCallBack.getInstance().countDownObjs.clear();
                        ActivityTaskManager.getInstance().closeAllActivity();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        return;
                    }
                    Intent intent = new Intent(context, MyBaskOrderActivity.class);
                    context.startActivity(intent);
                }
            });
        }

    }

    private class NoMoreHolder extends RecyclerView.ViewHolder {


        private RelativeLayout mRlFoot;
        private ProgressBar mPb;
        private TextView mFooterTv;
        private LinearLayout mEmpty;

        public NoMoreHolder(View itemView) {
            super(itemView);
            mRlFoot = itemView.findViewById(R.id.rl_foot);
            mPb = (ProgressBar) itemView.findViewById(R.id.pb_listview_footer);
            mFooterTv = (TextView) itemView.findViewById(R.id.listview_footer_tv);
            mEmpty = (LinearLayout) itemView.findViewById(R.id.empty);
        }

        public void bind(List<MyRecommendOrderBean> infos) {
            if (infos.size() == 1) {
                mRlFoot.setVisibility(View.GONE);
                mEmpty.setVisibility(View.VISIBLE);
            } else {
                mRlFoot.setVisibility(View.VISIBLE);
                mEmpty.setVisibility(View.GONE);
                mFooterTv.setText("无更多数据");
                mPb.setVisibility(View.GONE);
            }
        }
    }

    private class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout content_ll;   // 比赛信息
        ImageView prizeState_iv;   // 中奖情况（盖章图标）
        TextView time_tv;           // 发单时间
        TextView endTime_tv;        // 截止时间
        TextView amount_tv;         // 跟单彩金（订单彩金）
        TextView nChuan1_tv;        // 串关方式
        TextView type_tv;           // 保密方式
        Button btn_tz;              //投注详情
        Button btn_gd;              //跟单用户
        LinearLayout ll_tz;         //投注详情列表
        LinearLayout ll_gd;         //跟单用户列表
        LinearLayout ll_bt;

        public ViewHolder(View itemView) {
            super(itemView);
            content_ll = (LinearLayout) itemView.findViewById(R.id.myrr_item_content_ll);
            prizeState_iv = (ImageView) itemView.findViewById(R.id.myrr_item_prizestate_iv);
            time_tv = (TextView) itemView.findViewById(R.id.myrr_item_time);
            endTime_tv = (TextView) itemView.findViewById(R.id.myrr_item_endtime);
            amount_tv = (TextView) itemView.findViewById(R.id.myrr_item_amount);
            nChuan1_tv = (TextView) itemView.findViewById(R.id.myrr_item_n_chuan_1);
            type_tv = (TextView) itemView.findViewById(R.id.myrr_item_type);
            btn_tz = (Button) itemView.findViewById(R.id.btn_tz);
            btn_gd = (Button) itemView.findViewById(R.id.btn_gd);
            ll_tz = (LinearLayout) itemView.findViewById(R.id.hiscenter_tz_content);
            ll_gd = (LinearLayout) itemView.findViewById(R.id.hiscenter_gd_content);
            ll_bt = (LinearLayout) itemView.findViewById(R.id.ll_bt);
        }

        public void bind(MyRecommendOrderBean info, int position) {
            if (info.getOrderResultStatus() == 3 || info.getOrderResultStatus() == 4) { // 中奖
                prizeState_iv.setVisibility(View.VISIBLE);
                prizeState_iv.setImageDrawable(context.getResources().getDrawable(R.drawable.myrr_prizestate_yes_icon));
            } else if (info.getOrderResultStatus() == 2) {   // 未中奖
                prizeState_iv.setVisibility(View.VISIBLE);
                prizeState_iv.setImageDrawable(context.getResources().getDrawable(R.drawable.myrr_prizestate_no_icon));
            } else if (info.getOrderResultStatus() == 6) {   // 流单
                prizeState_iv.setVisibility(View.VISIBLE);
                prizeState_iv.setImageDrawable(context.getResources().getDrawable(R.drawable.myrr_prizestate_liu_icon));
            } else {    // 未开奖
                prizeState_iv.setVisibility(View.GONE);
            }

            time_tv.setText(info.getReceiveTime());
            endTime_tv.setText("截止：" + info.getEndTime());

            MyRecommendOrderBean.DetailBean detailBean = info.getDetail();

            amount_tv.setText("方案彩金：" + info.getAmount() / 100 + "米");

            nChuan1_tv.setText("过关方式：" + detailBean.getPlayName());

            boolean isEnd = false;  // 比赛是否截止
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  // 2017-07-22 00:00:00
            long endTime = 0;
            try {
                endTime = format.parse(info.getEndTime()).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            isEnd = endTime < System.currentTimeMillis();

            if (info.isShowTz()) {
                ll_gd.setVisibility(View.GONE);
                btn_tz.setTextColor(Color.parseColor("#e91e63"));
                btn_gd.setTextColor(Color.parseColor("#666666"));
                if (type != 0 && info.getWay() != 0 && !isEnd) {   // 方案保密
                    type_tv.setVisibility(View.VISIBLE);
                    ll_tz.setVisibility(View.GONE);
                } else {
                    type_tv.setVisibility(View.GONE);
                    ll_tz.setVisibility(View.VISIBLE);
                    setContent(ll_tz, detailBean.getRaceBetcode());
                }
            } else {
                type_tv.setVisibility(View.GONE);
                ll_tz.setVisibility(View.GONE);
                ll_gd.setVisibility(View.VISIBLE);
                btn_gd.setTextColor(Color.parseColor("#e91e63"));
                btn_tz.setTextColor(Color.parseColor("#666666"));
            }
            ll_bt.setVisibility(View.GONE);
        }

    }

    private void setContent(LinearLayout content_ll, List<MyRecommendOrderBean.DetailBean.RaceBetcodeBean> raceInfos) {
        content_ll.removeAllViews();
        for (int i = 0; i < raceInfos.size() + 1; i++) {
            View itemView = LayoutInflater.from(context).inflate(R.layout.view_myrr_content, null);
            RelativeLayout center_rl = (RelativeLayout) itemView.findViewById(R.id.myrr_content_rl);
            TextView matchId_tv = (TextView) itemView.findViewById(R.id.myrr_content_matchid);
            TextView homeAndAway_tv = (TextView) itemView.findViewById(R.id.myrr_content_home_and_away);
            TextView betCode_tv = (TextView) itemView.findViewById(R.id.myrr_content_betcode);
            TextView line_tv = (TextView) itemView.findViewById(R.id.myrr_content_line_tv);

            if (i == 0) {
                center_rl.setBackgroundColor(context.getResources().getColor(R.color.color_f5f5f5));

            } else {
                MyRecommendOrderBean.DetailBean.RaceBetcodeBean raceInfo = raceInfos.get(i - 1);
                center_rl.setBackgroundColor(context.getResources().getColor(R.color.white));
                matchId_tv.setText(raceInfo.getOfficialWeekDay() + raceInfo.getMatchNum());
                homeAndAway_tv.setText(raceInfo.getHomeTeam() + "\n vs \n" + raceInfo.getAwayTeam());
                String betCodes = "";   // 投注内容
                String results = "";    // 比赛结果
                for (int j = 0; j < raceInfo.getContents().size(); j++) {
                    betCodes += raceInfo.getContents().get(j).getBetcode() + " ";
                }
                betCode_tv.setText(Html.fromHtml(betCodes, null, null));

            }

            if (i == raceInfos.size()) {
                line_tv.setVisibility(View.GONE);
            } else {
                line_tv.setVisibility(View.VISIBLE);
            }
            content_ll.addView(itemView);
        }
    }

    public void setInfos(List<MyRecommendOrderBean> infos, int type) {
        this.infos = infos;
        this.type = type;
        this.notifyDataSetChanged();
    }

    public void setInfos(final boolean enabled) {

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mIsLoadingMore = false;
                mIsLoadMoreEnabled = enabled;
                notifyDataSetChanged();
            }
        });
    }
}
